﻿using System;
using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm;
using System.Collections.Generic;
using IN.Module;
using System.Collections.ObjectModel;
using IN.Util;
using DevExpress.Mvvm.POCO;
using System.Windows;
using DevExpress.Xpf.Bars;
using IN.DX.Common.Unity;
using IN.Interface;
using System.Reflection;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Media;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using IN.Util;
using IN.Module;
using IN.DX.WS_Base;
/// <summary> 
/// Industry Software
/// Copyright (c) 2020-2025  
/// 创 建：吴松
/// 描 述：主界面
/// </summary> 
namespace IN.DX.WS_Home
{
    [POCOViewModel]
    public class MainViewModel : ViewModelBase
    {
        private readonly Sys_MenuBll MenuBll = new Sys_MenuBll();
        private readonly TB_UserBll UserBll = new TB_UserBll();

        private List<string> LoadedNode = new List<string>();

        private ObservableCollection<BarSubItem> _MenuTreeList;
        public ObservableCollection<BarSubItem> MenuTreeList
        {
            get { return _MenuTreeList; }
            set
            {
                _MenuTreeList = value;
                RaisePropertyChanged();
            }
        }
        public MainViewModel()
        {

            Messenger.Default.Register<string>(this, "LoginIn_Success", InitData);
            //初始化一个用户登录账号
            //InitData("165F4951-1244-453F-887F-1E1A73BBA449");
        }

        private void InitData(string userid)
        {
            if (string.IsNullOrEmpty(userid)) userid = GlobalBLL.SysUser.UserID;
            TB_UserEntity user = UserBll.GetModelByID(userid);
            if (user == null) return;
            if (string.IsNullOrEmpty(user.RoleID)) return;

            ObservableCollection<TreeModel>  MenuTreeList1 = new ObservableCollection<TreeModel>(MenuBll.GetMenuTreeByRoleID(user.RoleID));
            MenuTreeList = LoadMenu(MenuTreeList1);
        }
        #region 命令
        //命令
        private DelegateCommand _LoadCommand;
        public DelegateCommand LoadCommand
        {
            get
            {
                if (_LoadCommand == null)
                {
                    _LoadCommand = new DelegateCommand(() => InitData("")); ;
                }
                return _LoadCommand;
            }
            set { _LoadCommand = value; }
        }

        #endregion
        public static MainViewModel Create()
        {
            return ViewModelSource.Create(() => new MainViewModel());
        }

        #region 加载菜单
        private ObservableCollection<BarSubItem> LoadMenu(ObservableCollection<TreeModel> list)
        {
            ObservableCollection<BarSubItem> MenuTop = new ObservableCollection<BarSubItem>();
            foreach (TreeModel temp in list) //第一级菜单必须为BarSubItem
            {
                
                if (string.IsNullOrEmpty(temp.parentId))
                {
                    BarSubItem TopSubItem = new BarSubItem();
                    TopSubItem.Content = temp.text;
                    TopSubItem.GlyphSize = GlyphSize.Large;
                    //加载图标
                    TopSubItem.Glyph = byteToImageSource(temp.Imageicon);

                    var tempOs = new ObservableCollection<TreeModel>(temp.ChildNodes);
                    ;
                    TopSubItem.ItemLinksSource= GetMenuNode(tempOs).Items;
                    MenuTop.Add(TopSubItem);
                }
            }
            return MenuTop;
        }

        //递归查询,找到返回该节点
        private BarSubItem GetMenuNode (ObservableCollection<TreeModel> node)
        {
            BarSubItem Menu = new BarSubItem();
            foreach (TreeModel temp in node) //第一级菜单必须为BarSubItem
            {
                BarSubItem MenuSubItem = new BarSubItem();
                //if (!temp.isvisible) break;
                if (temp.ChildNodes.Count != 0)
                {
                    BarSubItem barSubItem = new BarSubItem();
                    //加载图标
                    
                    var tempOs = new ObservableCollection<TreeModel>(temp.ChildNodes);
                    barSubItem = GetMenuNode(tempOs);
                    barSubItem.Content = temp.text;
                    barSubItem.Glyph = byteToImageSource(temp.Imageicon);
                    barSubItem.BarItemDisplayMode = BarItemDisplayMode.ContentAndGlyph;
                    Menu.Items.Add (barSubItem);
                }
                if (temp.ChildNodes.Count == 0)
                {
                    BarButtonItem barButtonItem = new BarButtonItem();
                    barButtonItem.DataContext = temp;
                    barButtonItem.Content = temp.text;

                    //加载自启动窗体
                    if(temp.autoshow)
                    {
                        OpenView(temp);
                    }
                    //加载图标
                    barButtonItem.Glyph = byteToImageSource(temp.Imageicon);

                    barButtonItem.ItemClick += BarButtonItem_ItemClick;
                    Menu.Items.Add(barButtonItem);
                }
            }
            return Menu;
        }

        private void BarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            TreeModel treeModel = (sender as BarButtonItem).DataContext as TreeModel;

            OpenView(treeModel);
        }

        //打开窗体
        private void OpenView( TreeModel model)
        {
            try
            {
                if ("WinForm" == model.wpforwinform) //WinForm窗体
                {
                    if(model.ShowStyle)  //弹窗
                    {
                        Type type = Type.GetType(model.formname + "," + model.formssembly);
                        if (type != null)
                        {
                            object obj = System.Activator.CreateInstance(type);
                            if (obj is XtraForm)
                            {
                                XtraForm fm = obj as XtraForm;
                                fm.ShowDialog();
                            }
                        }
                    }
                    else      //页面
                    {
                        object fm = null;
                        if (model.isDesignForm)  //界面设计器  设计的窗体
                        {
                            //if (!string.IsNullOrEmpty(model.formname))//如果是 界面设计器 的窗体
                            //{
                            //    var txtReader = new StreamReader(System.Windows.Forms.Application.StartupPath + @"\" + model.formname);
                            //    string layoutString = txtReader.ReadToEnd();
                            //    txtReader.Close();

                            //    var form = new CustomForm();
                            //    form.LayoutXml = layoutString;
                            //    fm = form as object;
                            //    (fm as Form).TopLevel = false;
                            //    (fm as Form).FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                            //    (fm as Form).StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation;
                            //    (fm as Form).WindowState = System.Windows.Forms.FormWindowState.Normal;
                            //    (fm as Form).AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
                            //    (fm as Form).BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                            //}
                        }
                        else
                        {
                            Type type = Type.GetType(model.formname + "," + model.formssembly);
                            if (type != null)
                            {
                                fm = System.Activator.CreateInstance(type);
                                (fm as XtraForm).TopLevel = false;
                                (fm as XtraForm).FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                                (fm as XtraForm).StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation;
                                (fm as XtraForm).WindowState = System.Windows.Forms.FormWindowState.Normal;
                                (fm as XtraForm).AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
                                (fm as XtraForm).BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;

                            }
                        }
                        var obj = ServiceProvider.Instance.Get<IDataBase>(model.viewmodel); //us.DataContext = obj;
                        MethodInfo method = obj.GetType().GetMethod("SetDBButton"); //SetDBButton是newuBaseViewModel中按钮加载方法
                        if (method != null)
                        {
                            method.Invoke(obj, new object[] { model.id, GlobalBLL.SysUser.RoleID });
                        }
                        if(obj!=null && fm!=null)
                        {
                            BaseFormViewModel formModel = obj as BaseFormViewModel;
                            if(formModel!=null)
                            {
                                formModel.ContentControl = fm;
                            }
                        }
                        CreateDocument(obj, model);
                    }
                }
                else                              //Wpf窗体
                {
                    if (!string.IsNullOrEmpty(model.viewmodel))
                    {
                        var obj = ServiceProvider.Instance.Get<IDataBase>(model.viewmodel); //us.DataContext = obj;
                        MethodInfo method = obj.GetType().GetMethod("SetDBButton"); //SetDBButton是newuBaseViewModel中按钮加载方法
                        if (method != null)
                        {
                            method.Invoke(obj, new object[] { model.id, GlobalBLL.SysUser.RoleID });
                        }
                        CreateDocument(obj, model);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(model.value))
                        {
                            Assembly assembly = Assembly.GetExecutingAssembly();
                            // 实例化窗体
                            Window win = assembly.CreateInstance(model.value) as Window;
                            win.ShowDialog();

                        }
                    }

                }

                
            }
            catch(Exception ex)
            {
                MessageBoxService.Show("加载窗体失败:" + ex.Message);
            }
        }

        #endregion


        //加载图标 转换二进制数据到ImageSource
        private ImageSource byteToImageSource(byte[] byteStream)
        {

            if ((byteStream) != null)
            {
                Stream stream = new MemoryStream(byteStream);
                Bitmap bitmapImage = new Bitmap(stream, true);
                ImageSource imageSource = Imaging.CreateBitmapSourceFromHBitmap(
                                          bitmapImage.GetHbitmap(),
                                          IntPtr.Zero,
                                          Int32Rect.Empty,
                                          BitmapSizeOptions.FromEmptyOptions());
                return imageSource;
            }
            return null;

        }

        protected virtual IMessageBoxService MessageBoxService { get { return ServiceContainer.GetService<IMessageBoxService>(); } }
        protected IDocumentManagerService DocumentManagerService { get { return this.GetService<IDocumentManagerService>("tabService"); } }
        protected IWindowService WindowService { get { return this.GetService<IWindowService>("windowService"); } }
        private void CreateDocument(object arg, TreeModel treeModel)
        {
            IDocument doc = DocumentManagerService.FindDocumentById(arg.ToString());
            
            if (doc == null)
            {
                if("WinForm"==treeModel.wpforwinform)//WinForm窗体
                {
                    doc = DocumentManagerService.CreateDocument(treeModel.value, arg);
                }
                else
                {
                    if (treeModel.ShowStyle)//窗体
                    {
                        foreach (Setter setter in ((DevExpress.Mvvm.UI.WindowService)WindowService).WindowStyle.Setters)
                        {
                            if (setter.Property.Name.Equals("Width")) //可后续修改窗体宽度
                            {

                            }
                            else if (setter.Property.Name.Equals("WindowStyle")) //可后续调整窗体大小
                            {
                                if (!setter.IsSealed) setter.Value = WindowStyle.None;
                            }
                        }
                        //doc = WindowService.CreateDocument();
                        WindowService.Show(treeModel.value, arg);
                        return;

                    }
                    else                //页面
                    {
                        doc = DocumentManagerService.CreateDocument(treeModel.value, arg);
   
                    }
                }
                //自动打开的窗体不允许关闭
                if(!treeModel.ShowStyle)
                {
                    if (treeModel.autoshow)
                    {
                        ((DevExpress.Xpf.Docking.Native.DockingDocumentUIServiceBase<DevExpress.Xpf.Docking.DocumentPanel, DevExpress.Xpf.Docking.DocumentGroup>.Document)doc).DocumentPanel.AllowClose = false;
                    }
                    else
                    {
                        ((DevExpress.Xpf.Docking.Native.DockingDocumentUIServiceBase<DevExpress.Xpf.Docking.DocumentPanel, DevExpress.Xpf.Docking.DocumentGroup>.Document)doc).DocumentPanel.AllowClose = true;
                    }
                }

                doc.Title = treeModel.text;
                doc.Id = arg.ToString();
                doc.Show();

            }
            else
            {
                doc.Show();
            }

        }

    }
}